package com.rybbaby.tss.platform.initializer;

import com.rybbaby.tss.core.initializer.AbstractAutomaticInit;
import com.rybbaby.tss.core.utils.SpringApplicationContextUtil;
import com.rybbaby.tss.platform.sysMenuPermissions.entity.SysMenuPermissions;
import com.rybbaby.tss.platform.sysMenuPermissions.service.ISysMenuPermissionsService;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 谢进伟
 * @description 菜单权限初始化器
 * @createDate 2016年11月23日 上午12:35:08
 */
public class MenuPermissionsInitializer extends AbstractAutomaticInit {

    private static Map<String, SysMenuPermissions> allMenuPermissions = new HashMap<String, SysMenuPermissions>();

    @Override
    public void autoInit() {
        load();
    }

    /**
     * 加载所有菜单权限
     */
    public static void load() {
        ExecutorService chedThread = Executors.newCachedThreadPool();
        chedThread.execute(new Runnable() {

            protected Logger log = Logger.getLogger(this.getClass());

            @Override
            public void run() {
                List<SysMenuPermissions> mpList = SpringApplicationContextUtil.getContext().getBean(ISysMenuPermissionsService.class).loadAll();
                if (allMenuPermissions != null && !mpList.isEmpty()) {
                    for (SysMenuPermissions sysMenuPermissions : mpList) {
                        allMenuPermissions.put(sysMenuPermissions.getId(), sysMenuPermissions);
                    }
                }
                if (allMenuPermissions.isEmpty()) {
                    log.warn("未设置任何菜单权限!");
                }
            }

        });
        chedThread.shutdown();
    }

    /**
     * 根据菜单Id 从缓存中获取菜单对象
     *
     * @param menuId 菜单Id
     * @return
     */
    public static SysMenuPermissions getMenuPermission(String menuId) {
        return allMenuPermissions.get(menuId);
    }

    /**
     * 递归找到指定菜单权限节点的所有父节点菜单权限
     *
     * @param smp     指定的菜单权限节点
     * @param parents 所有父节点菜单权限容器
     * @throws CloneNotSupportedException
     */
    public static void getMenuTree(SysMenuPermissions smp, Set<SysMenuPermissions> parents) throws CloneNotSupportedException {
        String parentSmpId = smp.getpId();
        if (parentSmpId == null) {// 本身为最顶层菜单节点,就没必要递归了
            return;
        }
        SysMenuPermissions parentSmp = allMenuPermissions.get(parentSmpId);
        if (parentSmp != null) {
            SysMenuPermissions newSmp = parentSmp.clone();
            newSmp.getChildrens().clear();
            parents.add(newSmp);
            if (newSmp.getpId() != null) {
                getMenuTree(newSmp, parents);
            }
        }
    }

}
